#ifndef __EMQX__H__
#define __EMQX__H__

#include <WiFiClient.h>
#include <PubSubClient.h>
#include "utils.h"

// MQTT Broker
const char* mqtt_broker = "106.12.111.47";
const char* subscribeTopic = "water_ox/androidToDevice1001";
const char* publishTopic = "water_ox/device1001ToAndroid";
const char* mqtt_username = "admin";
const char* mqtt_password = "whiteone@lu";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  messageFromEMQX = "";
  for (int i = 0; i < length; i++) {
    messageFromEMQX += ((char)payload[i]);
  }
  Serial.println(messageFromEMQX + "\n");
  Serial.println("-----------------------");
  deserializeJson(doc, messageFromEMQX); //开始使用Json解析
  if (doc["message"] == "use") {
    userCardId = doc["userCardId"].as<String>();
    //调用API接口获取卡余额
    String api = API + "user/getUserBalanceByUserCardId?userCardId=" + userCardId;
    Serial.println(api);
    HTTPClient http;
    http.begin(api); //HTTP begin
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.printf("HTTP Get Code: %d\r\n", httpCode);
      if (httpCode == HTTP_CODE_OK) { // 收到正确的内容
        String resBuff = http.getString();
        //	输出示例：{"mid":123456789,"following":226,"whisper":0,"black":0,"follower":867}}
        //	输出示例：{"code":"200","userBalance":80.48}
        Serial.println(resBuff);
        deserializeJson(doc, resBuff); //开始使用Json解析
        if (doc["code"] == "200") {
          userBalance = doc["userBalance"];
          Serial.println(userCardId + "'s balance:" + userBalance);
          pricePerSecond = doc["pricePerSecond"];
          // 开始计时
          if (!getLocalTime(&time0)) {
            display.println("Failed to obtain time");
            return;
          }
          isUsing = true;
          isEMQXUsing = true;
          digitalWrite(LED, HIGH);
          return;
        }
        else {
          return;
        }
      }
    }
    else {
      Serial.printf("HTTP Get Error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
  }
  else if (doc["message"] == "stop") {
    isUsing = false;
    isEMQXUsing = false;
    digitalWrite(LED, LOW);
    stopUsing(userCardId, usedTime);
    client.publish(publishTopic, "{\"status\":\"stop\"}");
  }
}

void initEMQX() {
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "esp32-client-";
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Public emqx mqtt broker connected");
    }
    else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
  //client.publish(publishTopic, "{\"device\":\"1001\",\"status\":\"online\",\"location\",\"梧州学院科技楼K801\"}");
  client.subscribe(subscribeTopic);
}



#endif 